import axios from 'axios';
/**
 * @param url 请求的url
 * @param data post发送的数据
 */
const $http = axios.create({
    timeout:3000,
    requestHeader: {'Content-Type': 'application/x-www-form-urlencoded'}
})
export default {
    http,
    // httpGet,
    digitUp,
    dateFormat,
    isTel,
    deepCopy,
    getWeek,
    isEmail,
    isCardId,
    $http
}
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 响应拦截，状态码为1005时，返回登录页，里面可以添加loading
axios.interceptors.response.use(res => {
    if (res.data.resultCode == 1005||res.data.resultCode==1003) {
        let hrefUrl = window.location.href;
        let indexNum = hrefUrl.indexOf("#");
        let hashUrl = hrefUrl.split("#");
        hashUrl.splice(1,1,"/login");
    let url = hashUrl.join("#");
    // alert(666);
    // window.location.href = "http://www.mx-credit.com";
    // Message("请登录");
    // function getCookie(name){
    //     var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    //     if(arr=document.cookie.match(reg)){
    //         return (arr[2]);
    //     }else{
    //         return null;
    //     }
    // }
    //删除cookies
    // function delCookie(name){
    //     var exp = new Date();
    //     exp.setTime(exp.getTime() - 1);
    //     var cval=getCookie(name);
    //     if(cval!=null){
    //         document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    //     }
    // }
    // delCookie("userId");
}
return res;
});
function deepCopy(o){
        if (o instanceof Array) {
            var n = [];
            for (var i = 0; i < o.length; ++i) {
                n[i] = this.deepCopy(o[i]);
            }
            return n;

        } else if (o instanceof Object) {
            var n = {}
            for (var i in o) {
                n[i] = this.deepCopy(o[i]);
            }
            return n;
        } else {
            return o;
        }
}
function http (url,data,callback) {
    let config = {
        method: 'post',
        url: url,
        params: data,
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        requestHeader: {'Content-Type': 'application/x-www-form-urlencoded'}
    };
    axios(config).then(callback);
}
function getWeek(fn){
    var arr = [];
    var currentDate = "";
    var aryDay = new Array("一", "二", "三", "四", "五", "六", "日");
    var date = new Date; //获取完整日期
    var year = date.getFullYear(); //获取当前年份
    var currentMonth = (date.getMonth()+1)>9?(date.getMonth()+1):"0"+(date.getMonth()+1);
    var currentDay = date.getDate()>9?date.getDate():"0"+date.getDate();
    currentDate = year+"-"+currentMonth+"-"+currentDay;
    var month = "";
    var d = "";
    function getDays() {
        var days = new Array();
        for (var i = 0; i <7; i++) {
            days[i] = getWeek(i+1);
        }
        return days;
    }
    //取得当前日期一周内的某一天
    function getWeek(i) {
        var now = new Date();
        var n = now.getDay();
        var start = new Date();
        start.setDate(now.getDate() - n + i); //取得一周内的第一天、第二天、第三天...
        return start;
    }
    arr = getDays();
    var weekObjArr = [];
    for(var j =0; j < arr.length; j++){
        var obj = {};
        month = (arr[j].getMonth() + 1)>9?(arr[j].getMonth() + 1):"0"+(arr[j].getMonth() + 1);
        d = arr[j].getDate()>9?arr[j].getDate():"0"+arr[j].getDate();
        obj.dateStr = year+"-"+month+ "-" + d;
        obj.weekStr = aryDay[j];
        weekObjArr.push(obj);
    }
    fn(weekObjArr,currentDate)
}


/**
 * 数字金额大写转换(可以处理整数,小数,负数
 * @param n
 * @returns {string}
 */
function digitUp (n) {
    var fraction = ['角', '分'];
    var digit = [
        '零', '壹', '贰', '叁', '肆',
        '伍', '陆', '柒', '捌', '玖'
    ];
    var unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
    ];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);
    var s = '';
    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);
    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元')
            .replace(/(零.)+/g, '零')
            .replace(/^整$/, '零元整');
};


/**
 *
 * @param obj 日期对象或者字符串
 * 日期的格式转换
 * @returns {string}
 */
function dateFormat(obj){
    if(typeof obj==="object"){
        let year = obj.getFullYear();
        let month = obj.getMonth()+1>9?obj.getMonth()+1:"0"+(obj.getMonth()+1);
        let todayDate = obj.getDate()>9? obj.getDate():"0"+obj.getDate();
        let h = obj.getHours()>9? obj.getHours():"0"+obj.getHours();
        let m = obj.getMinutes()>9? obj.getMinutes():"0"+obj.getMinutes();
        let s = obj.getSeconds()>9? obj.getSeconds():"0"+obj.getSeconds();
        return year+'-'+month+'-'+todayDate+" "+h+":"+m+":"+s;
    }
    if(typeof obj==="string"){
        return obj;
    }
}
/**
 *
 * @param obj 日期对象
 * @returns {string} 2017-07
 */
function dateFormatMon(obj){

    if(typeof obj==="object"){
        let year = obj.getFullYear();
        let month = obj.getMonth()+1;
        if(month<10){
            month='0'+month;
        }
        return year+'-'+month;
    }else{
        return obj;
    }

}


/**
 *
 * @param arr 自定义的数据模型 是个数组
 */
function jsonFormat(arr){

}

/**
 *
 * @param phone 手机号
 * @returns {boolean}
 */

function isTel(phone){
     return  /^1[34578]\d{9}$/.test(phone);
}
function isEmail(str){
    return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(str);
}
function isCardId(str){
    return /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(str);
}

/**
 * 判断是否是数字
 * @param num
 * @returns {boolean}
 */
function isNum(num){
    return  /^[1-9]+[0-9]*]*$/.test(num);
}

/**
 * 金钱格式转换
 * @param num
 * @returns {boolean}
 */
function currency(num){
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    var cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num + '.' + cents);
}


